<template>
  <div class="pr-4" v-loading="loading">
    <div class="bg-white p-2">
      <div class="flex justify-around w-300px m-auto">
        <Select
          :options="selectOptions"
          style="width: 180px"
          v-model:value="currentCode"
          @change="handleSelected"
        />
        <a-button type="primary" @click="customSubmitFunc" class="ml-2" :loading="loading"
          >保存</a-button
        >
      </div>
    </div>
    <div class="mt-2">
      <AceEditor v-model:value="scriptStr" :readonly="false" style="height: calc(100vh - 230px)" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref, onMounted, nextTick } from 'vue';
  import { Select } from 'ant-design-vue';
  import { AceEditor } from '/@/components/AceEditor/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getVisualGetModuleCss, getVisualUpdateModuleCss } from '/@/api/module/module';

  const props = defineProps({
    moduleCode: {
      type: String,
      default: '',
    },
    formCode: {
      type: String,
      default: '',
    },
  });
  const { t } = useI18n();

  const scriptStr = ref('');
  const loading = ref(false);
  const currentCode = ref('moduleList');
  const { createMessage } = useMessage();

  const selectOptions = ref([
    {
      value: 'moduleList',
      label: '列表页',
    },
    {
      value: 'add',
      label: '添加页',
    },
    {
      value: 'edit',
      label: '修改页',
    },
    {
      value: 'show',
      label: '详情页',
    },
  ]);
  const customSubmitFunc = async () => {
    try {
      loading.value = true;
      createMessage.success(t('common.opSuccess'));
      const params: any = {
        moduleCode: props.moduleCode,
        pageType: unref(currentCode),
        css: unref(scriptStr),
      };
      await getVisualUpdateModuleCss(params);
      await getAdminFlowGetEventScriptData();
    } catch (err) {
      console.error(err);
    } finally {
      loading.value = false;
    }
  };

  const getAdminFlowGetEventScriptData = async () => {
    if (!unref(currentCode)) {
      scriptStr.value = '';
      return;
    }
    const params: any = {
      moduleCode: props.moduleCode,
      pageType: unref(currentCode),
    };
    const { css } = await getVisualGetModuleCss(params);
    scriptStr.value = css;
  };

  const fetch = async () => {
    await nextTick();
    await getAdminFlowGetEventScriptData();
  };

  const handleSelected = () => {
    getAdminFlowGetEventScriptData();
  };

  onMounted(fetch);
</script>
